# coding:utf-8
import codecs
from bs4 import BeautifulSoup
import xlwt

workbook = xlwt.Workbook()
sheet1 = workbook.add_sheet('sheet1', cell_overwrite_ok=True)
title_row = [u'公司名称', u'法人代表', u'注册资金', u'注册时间', u'公司地址']
for i in range(0, len(title_row)):
    sheet1.write(0, i, title_row[i])

file_list = [
    'p2.html',
    'p1.html',

    'p3.html',
    'p4.html',
    'p5.html'
]
line_number = 1
for html_file in file_list:
    f = codecs.open(html_file)
    html_doc = f.read()

    soup = BeautifulSoup(html_doc, 'lxml')
    items = soup.findAll(name='div', class_='search_result_single')

    css_rules = {
        'legal': 'div.search_right_item > div.search_row_new.pt20 > div:nth-of-type(1) > div:nth-of-type(1) > span',
        'capital': 'div.search_right_item > div.search_row_new.pt20 > div:nth-of-type(1) > div:nth-of-type(2) > span',
        'time': 'div.search_right_item > div.search_row_new.pt20 > div:nth-of-type(1) > div:nth-of-type(3) > span',
        'address': 'div.search_right_item > div.search_row_new.pt20 > div:nth-of-type(2) > div > span.overflow-width.over-hide.vertical-bottom.in-block'}

    '''
    body > div > div.search_right_item > div.search_row_new.pt20 > div:nth-child(2) > div > span.overflow-width.over-hide.vertical-bottom.in-block
    body > div > div.search_right_item > div.search_row_new.pt20 > div:nth-child(2) > div > span.overflow-width.over-hide.vertical-bottom.in-block
    body > div > div.search_right_item > div.search_row_new.pt20 > div:nth-child(2) > div > span.overflow-width.over-hide.vertical-bottom.in-block

    '''

    for item in items:
        if not item:
            continue
        # with codecs.open(str(line) + 'prettify.html', 'w', encoding='utf-8') as f:
        #     f.write(item.prettify())
        name = item.span.text
        legal = item.select(css_rules['legal'])
        registered_capital = item.select(css_rules['capital'])
        registered_time = item.select(css_rules['time'])
        address = item.select(css_rules['address'])
        legal = legal[0].text if legal else '-'
        registered_capital = registered_capital[0].text if registered_capital else '-'
        registered_time = registered_time[0].text if registered_time else '-'
        address = address[0].text if address else '-'
        row_data = [name, legal, registered_capital, registered_time, address]
        for i in range(0, len(title_row)):
            sheet1.write(line_number, i, row_data[i])
        line_number += 1

    f.close()

workbook.save('message.xls')